package com.nulldev.util.concurrency.threadIt;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

public class ThreadUtils {
	public static void kill(final Thread... threads) {
		for (final Thread t : threads) {
			if (t != null) {
				try {
					if (t.isDaemon()) {
						t.setDaemon(false);
					}
					t.interrupt();
				} catch (Throwable e) {
				}
			}
		}
	}

	private static final long SLEEP_PRECISION = TimeUnit.MILLISECONDS.toNanos(2);
	private static final long SPIN_YIELD_PRECISION = TimeUnit.MILLISECONDS.toNanos(2);

	public static void sleepNanos(long nanoDuration) throws InterruptedException {
		final long end = System.nanoTime() + nanoDuration;
		long timeLeft = nanoDuration;
		do {
			if (timeLeft > SLEEP_PRECISION)
				Thread.sleep(1);
			else if (timeLeft > SPIN_YIELD_PRECISION)
				Thread.yield();
			timeLeft = end - System.nanoTime();
		} while (timeLeft > 0);
	}

	public static void stackTraceAll() {
		final Collection<java.lang.StackTraceElement[]> stackTraces = java.lang.Thread.getAllStackTraces().values();
		for (java.lang.StackTraceElement[] traces : stackTraces) {
			System.out.println("==========");
			for (java.lang.StackTraceElement trace : traces) {
				System.out.println(trace.toString());
			}
		}
	}
}
